﻿using System;
using Microsoft.Silverlight.Testing.Harness;
using Microsoft.Silverlight.Testing.UnitTesting.Harness;
using Objectware.Silverlight.Testing.TestProject.TestResultService;
using System.Threading;

namespace Objectware.Silverlight.Testing.TestProject
{
	public class UnitTestResultProvider : LogProvider
	{
		private static readonly TestResultService.TestResultService TestResultService =
			ServiceLocator.Default.GetInstance<TestResultService.TestResultService>();

		private static void AddResult(string testClass, string testMethod, string information, object additionalInformation, string result)
		{
			if( null == additionalInformation )
			{
				additionalInformation = string.Empty;
			}

			var methodResult = TestMethodResult.Passed;
			switch( result.ToLower() )
			{
				case "passed":
					{
						methodResult = TestMethodResult.Passed;
					}
					break;
				case "inconclusive":
					{
						methodResult = TestMethodResult.Inconclusive;
					}
					break;
				case "error":
					{
						methodResult = TestMethodResult.Error;
					}
					break;
			}


			TestResultService.BeginReportResult(
				testClass, 
				testMethod, 
				information, 
				additionalInformation.ToString(),
				methodResult,
				(o)=> ServiceHelper.ExecuteMethod(() =>
				                                  TestResultService.EndReportResult(o)),null);
		}

		


		protected override void ProcessRemainder(LogMessage message)
		{
			switch (message.MessageType)
			{
				case LogMessageType.TestResult:
					{
						if (message.Decorators.ContainsKey(UnitTestLogDecorator.ScenarioResult))
						{
							var result = message.Decorators[UnitTestLogDecorator.ScenarioResult] as ScenarioResult;

							ServiceHelper.ExecuteMethod(() =>
							                            AddResult(result.TestClass.Name, result.TestMethod.Name, message.Message,
							                                      string.Empty,
							                                      result.Result.ToString()));
						}
					}
					break;
			}
			
		}
	}
}
